import { 
  Camera,  
  Mesh, 
  PlaneBufferGeometry, 
  Scene, 
  ShaderMaterial, 
  Vector3, 
  WebGLRenderer 
} from "three"

const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.style.width = '100vw'
canvas.style.height = '100vh'

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true,
  canvas
})
renderer.autoClearColor = false

const camera = new Camera()
camera.position.z = 1
const plane = new PlaneBufferGeometry(2, 3)

// 片元着色器
const fragmentShader = `
#include <common>

// 运行时间（以秒计）
uniform vec3 u_resolution;

// 定义一个函数
// 使用 y 值绘制一条直线
float plot(vec2 st) {
  return smoothstep(0.02, 0.0, abs(st.y - st.x));
}

void main() {
  // 格式化坐标，让值落在 0.0 到 1.0 之间
  vec2 st = gl_FragCoord.xy/u_resolution.xy;

  float y = st.x;

  vec3 color = vec3(y);

  // 绘制一条线
  float pct = plot(st);

  color = (1.0 - pct) * color + pct * vec3(0., 1., 0.);
  // color = (1.0 - pct) * color + pct * vec3(0., 1., 0.);

  // 将 x y 映射到红色与绿色通道
  gl_FragColor = vec4(color, 1.);
}
`

// 片元着色器
const fragmentShader2 = `
#include <common>

// 运行时间（以秒计）
uniform vec3 u_resolution;

// 定义一个函数
// 绘制一个曲线
float plot(vec2 st, float pct) {
  return smoothstep(pct - 0.02, pct, st.y) - 
         smoothstep(pct, pct + 0.02, st.y);
}

void main() {
  // 格式化坐标，让值落在 0.0 到 1.0 之间
  vec2 st = gl_FragCoord.xy/u_resolution.xy;

  float y = pow(st.x, 5.0);

  vec3 color = vec3(y);

  // 绘制一条线
  float pct = plot(st, y);

  color = (1.0 - pct) * color + pct * vec3(0., 1., 0.);

  // 将 x y 映射到红色与绿色通道
  gl_FragColor = vec4(color, 1.);
}
`

// const material = new MeshBasicMaterial({ color: 'red' })
const uniforms = {
  u_resolution: { value: new Vector3() },
}
const material = new ShaderMaterial({
  fragmentShader: fragmentShader2,
  uniforms
})
scene.add(new Mesh(plane, material))

function render(time) {
  // 转化成秒
  time *= 0.001

  const canvas = renderer.domElement
  uniforms.u_resolution.value.set(canvas.width, canvas.height, 1)

  renderer.render(scene, camera)

  requestAnimationFrame(render)
}

requestAnimationFrame(render)